<?php

namespace platform\models;

use common\services\Authorization;
use platform\core\BaseModel;
use cm;
use Yii;
use yii\helpers\Url;

class SiteModel extends BaseModel
{
    /*
    * 站点管理
    */
    public function actionIndex()
    {
        if (Cm::$req->isPost()) {
            $action = Cm::$req->get('action');
            switch ($action) {
                case "list":
                    $key = Cm::$req->post('key', ['null', 'empty', 'default' => '']);
                    $hot = (int)Cm::$req->post('is_hot', ['null', 'empty']);
                    $firstchar = Cm::$req->post('firstchar', ['null', 'empty']);
                    $province = Cm::$req->post('province', ['null', 'empty']);
                    $pageIndex = Cm::$req->post('page', ['null', 'empty', 'default' => 1]);
                    $pageCount = Cm::$req->post('limit', ['null', 'empty', 'default' => 20]);
                    $where = " 1=1 AND s.status=1 AND oc.status=1 ";
                    if(!empty($firstchar)){
                        $firstchar = trim(strtoupper($firstchar)); 
                        $where .= " AND s.firstchar='{$firstchar}'";
                    }
                    if(!empty($hot)){
                        $hot = $hot == 2 ? 0 : $hot;
                        $where .= " AND s.is_hot={$hot}";
                    }
                    if(!empty($province)){
                        $where .= " AND FIND_IN_SET('{$province}',oc.parentpath)";
                    }
                    if(!empty($key)){
                        $where .= " AND (s.name LIKE '%{$key}%' OR s.full_name LIKE '%{$key}%')";
                    }
                    $data = Cm::$db->paging("SELECT s.*,oc.province,oc.city,oc.full_name AS area,oc.parentpath,oc.level
                        FROM site s
                        INNER JOIN open_city oc ON oc.code=s.city_code
                        WHERE {$where} ORDER BY s.city_code ASC,s.sort ASC",
                        $pageIndex, $pageCount);
                    foreach ($data['data'] as $key => &$value) {
                        $city = $value['city'];
                        if(empty($city)){
                            $value['city'] = !empty($value['province']) && $value['province'] != $value['area'] ? $value['area'] : $value['city'];
                            $value['area'] = !empty($value['province']) && $value['province'] != $value['area'] ? '' : $value['area']; 
                        }
                        $province = $value['province'];  
                        if(empty($province)){
                            $value['province'] = $value['area'];
                            $value['area'] = '';  
                        }     
                        $codearr = explode(",", $value['parentpath']);
                        $value['province_code'] = $codearr[0];
                        $value['citys_code'] = empty($codearr[1]) ? 0 : $codearr[1];                  
                        $value['area_code'] = empty($codearr[2]) ? 0 : $codearr[2];                  
                    }    
                    Cm::$res->paging($data);
                    break;
                case 'save':
                    $id = Cm::$req->post('id', ['null', 'empty', 'default' => 0]);
                    $mdata = [
                        'city_code' => (int)Cm::$req->post('city_code', ['null', 'empty','default'=>0]), 
                        'name' => trim(Cm::$req->post('name',['title'=>'站点名称'])),
                        'full_name' => trim(Cm::$req->post('full_name',['title'=>'站点全称'])),
                        'serial_number' => trim(Cm::$req->post('serial_number',['title'=>'编码'])),
                        'firstchar' => trim(strtoupper(Cm::$req->post('firstchar',['title'=>'首字母']))),
                        'sort' => Cm::$req->post('sort', ['null', 'empty','default'=>0]),
                        'type' => Cm::$req->post('type', ['null', 'empty','default'=>0]),
                        'is_hot' => Cm::$req->post('is_hot',['null','empty','default'=>0]),
                        'updatetime' => date("Y-m-d H:i:s",time())
                    ];
                    if(empty($mdata['city_code'])){
                        Cm::$res->error('请选择所属的地区');
                    }
                    $hisserial_number = Cm::$db->one("SELECT id FROM site WHERE serial_number='{$mdata['serial_number']}' AND status=1 AND id!={$id}");
                    if (!empty($hisserial_number)) {
                        Cm::$res->error('该编码已存在');
                    }
                    if(!empty($id)){
                        Cm::$db->update('site', $mdata, "id={$id}");
                        Cm::$app->log->authlog(25,$mdata,$id);
                    }else{
                        $mdata['addtime'] = date('Y-m-d H:i:s');
                        $mdata['status'] = 1;
                        $id = Cm::$db->insert('site', $mdata);
                        if(!$id){
                            Cm::$res->error('保存失败');
                        }
                        Cm::$app->log->authlog(26,$mdata,$id);
                    }
                    Cm::$res->susess([], '保存成功');
                    break;      
                case 'del':
                    $id = Cm::$req->post('id', ['null', 'empty', 'default' => 0]);
                    if(empty($id)){
                        Cm::$res->error('删除失败,请选择删除开通的站点');
                    }
                    $mdata = ['status' => 2,'updatetime' => date("Y-m-d H:i:s",time())];
                    Cm::$db->update("site", $mdata, "id={$id}");
                    Cm::$app->log->authlog(27,$mdata,$id);
                    Cm::$res->susess();
                    break;    
            }
        }

        $data['map'] = [];
        $data['map'][] = ['title' => "站点管理", 'url' => Url::to(['site/index'])];
        $data['baseUrl'] = Url::to(['site/index']);
        $data['allOpenCity'] = $this->allOpenCity();
        $data['allFirstchar'] = $this->allFirstchar();
        $data['allProvince'] = $this->allProvince();
        return $data;
    }

    /*
    * 城市管理
    */
    public function actionArea(){
        if (Cm::$req->isPost()) {
            $action = Cm::$req->get('action');
            switch ($action) {
                case "list":
                    $key = Cm::$req->post('key', ['null', 'empty', 'default' => '']);
                    $firstchar = Cm::$req->post('firstchar', ['null', 'empty']);
                    $province = Cm::$req->post('province', ['null', 'empty']);
                    $is_hot = Cm::$req->post('is_hot', ['null', 'empty', 'default' => 0]);
                    $pageIndex = Cm::$req->post('page', ['null', 'empty', 'default' => 1]);
                    $pageCount = Cm::$req->post('limit', ['null', 'empty', 'default' => 20]);
                    $where = " 1=1 AND c.status=1 ";
                    if(!empty($firstchar)){
                        $where .= " AND c.firstchar='{$firstchar}' ";     
                    }
                    if(!empty($province)){
                        $where .= " AND FIND_IN_SET({$province},c.parentpath) ";     
                    }
                    if(!empty($is_hot)){
                        $is_hot = $is_hot == 2 ? 0 : $is_hot; 
                        $where .= " AND c.is_hot={$is_hot} ";         
                    }
                    if(!empty($key)){
                        $where .= " AND (c.name LIKE '%{$key}%' OR c.full_name LIKE '%{$key}%' OR c.province LIKE '%{$key}%' OR c.city LIKE '%{$key}%') ";
                    }
                    $data = Cm::$db->paging("SELECT c.*
                        FROM open_city c
                        WHERE {$where} ORDER BY c.code ASC",
                        $pageIndex, $pageCount);
                    if(!empty($data['data'])){
                        foreach ($data['data'] as $key => &$value) {
                            $value['lastname'] = empty($value['province']) && empty($value['city']) ? '' : (!empty($value['province']) && empty($value['city']) ? $value['province'] : $value['province']."--".$value['city'] );
                        }
                    }
                    Cm::$res->paging($data);
                    break;
                case 'save':
                    $id = Cm::$req->post('id', ['null', 'empty', 'default' => 0]);
                    $mdata = [
                        'name' => trim(Cm::$req->post('name',['title'=>'地区名称'])),
                        'full_name' => trim(Cm::$req->post('full_name',['title'=>'地区全称'])),
                        'serial_number' => trim(Cm::$req->post('serial_number',['title'=>'编码'])),
                        'code' => trim(Cm::$req->post('code', ['null', 'empty', 'default' => 0])),
                        'level' => Cm::$req->post('level', ['null', 'empty', 'default' => 0]),
                        'area_id' => (int)Cm::$req->post('area_id', ['null', 'empty', 'default' => 0]),
                        'short_pinyin' => trim(strtoupper(Cm::$req->post('short_pinyin',['title'=>'地区简拼']))),
                        'full_pinyin' => trim(strtolower(Cm::$req->post('full_pinyin',['title'=>'地区全拼']))),
                        'firstchar' => trim(strtoupper(Cm::$req->post('firstchar',['title'=>'首字母']))),
                        'province' => Cm::$req->post('province', ['null', 'empty']),
                        'city' => Cm::$req->post('city', ['null', 'empty']),
                        'is_hot' => Cm::$req->post('is_hot', ['null', 'empty', 'default' => 0]),
                        'parentpath' => Cm::$req->post('parentpath', ['null', 'empty']),
                        'updatetime' => date("Y-m-d H:i:s",time())
                    ];
                    if(empty($mdata['level'])){
                        Cm::$res->error('保存失败,请选择类型');
                    }
                    if(empty($mdata['parentpath']) || empty($mdata['code'])){
                        Cm::$res->error('保存失败,请正确选择地区');    
                    }
                    if(empty($mdata['area_id'])){
                        Cm::$res->error('保存失败,请选择地区');
                    }
                    $hisarea = Cm::$db->one("SELECT id,status FROM open_city WHERE area_id={$mdata['area_id']}");
                    if(!empty($hisarea)){
                        if($hisarea['status']==1){
                            if($id!=$hisarea['id']){
                                Cm::$res->error('保存失败,该地区已开通');
                            }
                        }else{
                            if($id!=0 && $id!=$hisarea['id']){
                                Cm::$db->delete("open_city","id={$hisarea['id']}");
                            }
                            if($id==0){
                                $id = $hisarea['id'];
                                $mdata['status'] = 1;
                            }
                            if($id!=0 && $id==$hisarea['id']){
                                $mdata['status'] = 1; 
                            }
                        }
                    }

                    $hisserial_number = Cm::$db->one("SELECT id FROM open_city WHERE serial_number={$mdata['serial_number']} AND status=1 AND id!={$id}");
                    if (!empty($hisserial_number)) {
                        Cm::$res->error('该编码已存在');
                    }
                    if(!empty($id)){
                        Cm::$db->update('open_city', $mdata, "id={$id}");
                        Cm::$app->log->authlog(30,$mdata,$id);
                    }else{
                        $mdata['addtime'] = date('Y-m-d H:i:s');
                        $mdata['status'] = 1;
                        $id = Cm::$db->insert('open_city', $mdata);
                        if(!$id){
                            Cm::$res->error('保存失败');
                        }
                        Cm::$app->log->authlog(29,$mdata,$id);
                    }
                    Cm::$res->susess([], '保存成功');
                    break;      
                case 'del':
                    $id = Cm::$req->post('id', ['null', 'empty', 'default' => 0]);
                    if(empty($id)){
                        Cm::$res->error('请选择删除开通的城市');
                    }
                    $mdata = ['status' => 2,'updatetime' => date("Y-m-d H:i:s",time())];
                    Cm::$db->update("open_city", $mdata, "id={$id}");
                    Cm::$app->log->authlog(28,$mdata,$id);
                    Cm::$res->susess();
                    break;    
            }
        }

        $data['map'] = [];
        $data['map'][] = ['title' => "站点管理", 'url' => Url::to(['site/index'])];
        $data['map'][] = ['title' => "城市管理", 'url' => Url::to(['site/area'])];
        $data['baseUrl'] = Url::to(['site/area']);
        $data['allFirstchar'] = $this->allFirstchar();
        $data['allProvince'] = $this->allProvince();
        $data['allArea'] = $this->allArea();
        return $data;
    }
}